<?php
	include_once 'dblib/dblib.php';
	
	/*
	 *  Υποθέτουμε ότι υπάρχει πίνακας "users" στη Βάση Δεδομένων με τα εξής πεδία:
	 *     username [κλειδί]
	 *     password
	 *     surname
	 *     forname
	 * /

	/*
	 * basic C.R.U.D. functions
	 */
	
	
	/*
	 * CREATE USER
	 * Return Values:
	 *    = 0: Success
	 *   != 0: Error
	 * 
	 *   Error Codes:
	 *     1: Username already exists
	 *     2: Error creating user
	 */
	function user_create($username, $password, $surname, $forname){
		//Πρώτα ελέγχουμε αν υπάρχει ήδη το username
		$user = user_read($username);
		
		
		if ($user) return 1;

		/*
		 * Προστασία από SQL injection
		 */		
		$username = mysql_real_escape_string($username);
		$password = mysql_real_escape_string($password);
		$surname = mysql_real_escape_string($surname);
		$forname = mysql_real_escape_string($forname);
		
		$query = "INSERT INTO `users` (`username`, `password`, `surname`, `forname`) VALUES ('{$username}', '{$password}', '{$surname}', '{$forname}')";
		$result = DBLib::execute_query($query);
		
		if ($result === FALSE) return 2;
		
		return 0;
	}
	
	
	/*
	 * READ USER
	 * Return Values:
	 *   - If the user was found, an object containing all user properties is returned
	 *   - If the user was not found, NULL is returned 
	 */
	function user_read($username){
		$rows = NULL;
		$num = 0;
		
		/*
		 * Προστασία από SQL injection
		 */		
		$username = mysql_real_escape_string($username);
		
		$query = "SELECT * FROM `users` WHERE `username` = '{username}'";
		DBLib::getrows($query, $rows, $num);
		
		//Αν δεν βρεθεί εγγραφή, επιστρέφουμε NULL
		if ($num == 0) return NULL;
		
	 	$user = mysql_fetch_object($rows);
		
		return $user;
	}
	
	function user_update($username, $password, $surname, $forname){
		/*
		 * Προστασία από SQL injection
		 */		
		$username = mysql_real_escape_string($username);
		$password = mysql_real_escape_string($password);
		$surname = mysql_real_escape_string($surname);
		$forname = mysql_real_escape_string($forname);
		
		$query = "UPDATE `users` SET `password` = '{$password}', `surname` = {$surname}, `forname` = '{$forname}' WHERE `username` = '{$username}'";
		$result = DBLib::execute_query($query);
		return $result;
	}
		
	function user_delete($username){
		/*
		 * Προστασία από SQL injection
		 */		
		$username = mysql_real_escape_string($username);
		
		$query = "DELETE FROM `users` WHERE `username` = '{$username}'";
		$result = DBLib::execute_query($query);
		return $result;
	}
	
	/*
	 * Login Function
	 */
	
	function login($username, $password){
		$user = user_read($username);
		
		//user does not exist
		if (!$user) return FALSE;
		
		if ($user->password == $password) return TRUE;
		else return FALSE;
	}
		
?>